from flask import Blueprint, request, jsonify, current_app
from api.models import Collection, User, CollectionItem
from api import db
from api.errors import bad_request, unauthorized
from api.routes.auth import token_required
from datetime import datetime

collection_bp = Blueprint('collection', __name__)

@collection_bp.route('/api/collection/create', methods=['POST'])
@token_required
def create_collection():
    """创建收藏夹"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data or 'name' not in data:
            return bad_request('请提供收藏夹名称')

        # 从请求头获取token
        token = request.headers.get('Authorization')
        if not token:
            return unauthorized('缺少token')
            
        # 根据token获取用户
        user = User.query.filter_by(token=token).first()
        if not user:
            return unauthorized('无效的token')

        # 验证收藏夹名称
        name = data['name'].strip()
        if not name or len(name) > 50:
            return bad_request('收藏夹名称长度不符合要求')

        # 检查用户是否已有同名收藏夹
        existing_collection = Collection.query.filter_by(
            user_id=user.id,
            name=name
        ).first()
        if existing_collection:
            return bad_request('已存在同名收藏夹')

        # 获取当前最大排序值
        max_sort = db.session.query(db.func.max(Collection.sort))\
            .filter_by(user_id=user.id).scalar() or 0

        # 创建新收藏夹
        collection = Collection(
            user_id=user.id,
            name=name,
            type=1,  # 自定义收藏夹
            sort=max_sort + 1
        )
        
        db.session.add(collection)
        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': collection.to_dict()
        })

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'创建收藏夹失败: {str(e)}')
        return bad_request('创建失败，请稍后重试') 

@collection_bp.route('/api/collection/items', methods=['POST'])
@token_required
def get_collection_items():
    """获取收藏夹内容"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data or 'collection_id' not in data:
            return bad_request('请提供收藏夹ID')

        # 从请求头获取token
        token = request.headers.get('Authorization')
        if not token:
            return unauthorized('缺少token')
            
        # 根据token获取用户
        user = User.query.filter_by(token=token).first()
        if not user:
            return unauthorized('无效的token')

        collection_id = data.get('collection_id')
        page = data.get('page', 1)
        per_page = data.get('per_page', 10)

        # 验证收藏夹是否存在且属于当前用户
        collection = Collection.query.filter_by(
            id=collection_id,
            user_id=user.id
        ).first()
        if not collection:
            return bad_request('收藏夹不存在或无权访问')

        # 分页查询收藏内容
        pagination = CollectionItem.query.filter_by(
            collection_id=collection_id,
            user_id=user.id
        ).order_by(
            CollectionItem.create_time.desc()
        ).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )

        items = [item.to_dict() for item in pagination.items]

        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'collection': collection.to_dict(),
                'items': items,
                'pagination': {
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'current_page': pagination.page,
                    'per_page': pagination.per_page
                }
            }
        })

    except Exception as e:
        current_app.logger.error(f'获取收藏夹内容失败: {str(e)}')
        return bad_request('获取失败，请稍后重试') 